const inquirer = require("inquirer")
const chalk = require("chalk")
const artTemplate = require("art-template")
const fs = require("fs")
const fse = require("fs-extra")
const path = require("path")

const question = require("./question.ts")

let connect

inquirer
  .prompt([question.host, question.port, question.username, question.password, question.dbName, question.tableName])
  .then(async (res) => {
    let columns = await queryTableColumns(res)
    inquirer.prompt([question.cols(columns), question.crud, question.queryParams(columns), question.moduleName]).then((ans) => {
      console.log(chalk.green("开始生成你所需要的代码模板"))
      let data = renderData(ans)

      // artTemplates
      // fs.readFile("./template/form.tpl", (err, txt) => {
      //   console.log("render data : ", data)
      //   let content = artTemplate.render(txt.toString(), data)
      //   console.log(chalk.red("final render file ==== \n", content))
      //   process.exit(0)
      // })
      let output = path.join(__dirname, '../src')
      console.log('output = ', data);
      
      buildFile("template/form.tpl", data, path.join(output, 'pages', data.moduleName, `${data.moduleName}FormPage.vue`))
      buildFile("template/list.tpl", data, path.join(output, 'pages', data.moduleName, `${data.moduleName}ListPage.vue`))
      buildFile("template/route.tpl", data, path.join(output, 'router/modules', `${data.moduleName}.route.ts`))
      buildFile("template/api.tpl", data, path.join(output, 'network/api', `${data.moduleName}.api.ts`))
    })
  })
  .catch((error) => {
    console.log("error == ", error)
  })

const queryTableColumns = async (res) => {
  console.log("开始连接数据库: ", res)
  let knex = require("knex")({
    client: "mysql", //指定knex要操作的数据库为MySQL
    connection: {
      host: res.host, //数据库地址
      user: res.username, //数据库登录名
      password: res.password, //数据库登录密码
      database: "information_schema", //要操作的库名称
    },
  })

  let result = await knex
    .select("column_name", "column_comment", "data_type")
    .from("columns")
    .where("table_schema", "=", res.dbName)
    .where("table_name", "=", res.tableName)

  return result
}

const renderData = (data) => {
  let rd = {
    moduleName: data.moduleName,
    cols: data.cols.map((t) => JSON.parse(t)),
    queryParams: data.cols.map((t) => JSON.parse(t)),
    crud: data.cols.map((t) => JSON.parse(t)),
  }

  if (data.crud.indexOf("C [添加]") > -1) {
    rd["insert"] = true
  }
  if (data.crud.indexOf("R [查询]") > -1) {
    rd["query"] = true
  }
  if (data.crud.indexOf("U [修改]") > -1) {
    rd["update"] = true
  }
  if (data.crud.indexOf("D [删除]") > -1) {
    rd["delete"] = true
  }
  return rd
}

const buildFile = (templatePath, data, output) => {
  // artTemplates
  console.log('buildFile', templatePath, output);
  
  let txt = fs.readFileSync(path.join(__dirname, templatePath))
  let content = artTemplate.render(txt.toString(), data)
  fs.writeFileSync(output, content)
  console.log('file: ', output, " 生成成功！");
  
}
